﻿using System.Collections.Generic;
using System.Text;

namespace Edu.Technion.CSE.OpenUnit4.CollectionsLib
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="V"></typeparam>
    public class Map<K, V> : IMap<K, V>
    {
        // Members

        private Dictionary<K, V> dict;

        // Constructors

        /// <summary>
        /// 
        /// </summary>
        public Map()
        {
            dict = new Dictionary<K, V>();
        }

        // Public Methods

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ContainsKey(K key)
        {
            return dict.ContainsKey(key);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public K[] GetAllKeys()
        {
            K[] keys = new K[dict.Count];             
            dict.Keys.CopyTo(keys, 0);
            return keys;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public V GetValue(K key)
        {
            V value;
            if (!dict.TryGetValue(key, out value))
            {
                value = default(V);
            }
            return value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Insert(K key, V value)
        {
            dict.Add(key, value);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public V Remove(K key)
        {
            V value;
            bool result = dict.TryGetValue(key, out value);
            dict.Remove(key);
            return value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder("[");
            K[] keys = GetAllKeys();
            for (int i = 0; i < keys.Length; ++i)
            {
                sb.Append(keys[i].ToString());
                sb.Append(":");
                sb.Append(GetValue(keys[i]).ToString());
                sb.Append(", ");
            }
            sb.Insert(sb.Length - 1, "]");
            return sb.ToString();
        }
    }
}
